function pconfigs = selectreturn(allMean,allCovar,r)
%SELECTRETURN portfolio configurations from 3D efficient frontier.
%   PCONFIGS = SELECTRETURN(ALLMEAN,ALLCOV,R) returns the portfolio configurations 
%   for a target return given the average return and covariance for a 
%   rolling efficient frontier.
%
%   Inputs:
%
%     ALLMEAN - A (Number of Curves)x1 cell array where each element is an 
%     1 x (Number of Assets) vector of the expected asset returns used to
%     generate each curve on the surface.
%            
%     ALLCOV - A (Number of Curves)x1 cell array where each element is an 
%     (Number of Assets) x (Number of Assets) vector of the covariance
%     matrix used to generate each curve on the surface.
%
%     R - Target return value for each curve in frontier. 
%
%   Output:
%
%     PCONFIGS - A (Number of assets) x (Number of curves) matrix of 
%     asset allocation weights needed to obtain the target rate of return.
%
%   See also FRONTIER.

%       Copyright 1995-2009 The MathWorks, Inc.
%       $Revision: 1.1.6.4 $   $Date: 2009/03/09 19:12:31 $

%Need target return to calculate weights
if nargin < 3
  error('finance:selectreturn:missingTargetReturn',...
        'Please specify a target return to calculate weights.')
end

%Convert matrices to cell arrays
if isa(allMean,'double')
  allMean = {allMean};
end
if isa(allCovar,'double')
  allCovar = {allCovar};
end

%Check that allMean and allCovar have same dimensions
if ~all(size(allMean) == size(allCovar))
  error('finance:finance:selectreturn','ALLMEAN and ALLCOV must be Mx1 cell arrays.')
end

numperiods = length(allMean);
pconfigs = NaN(length(allMean{1}),numperiods);

for i = 1:numperiods
    
  try
    [a,b,pconfigs(:,i)] = portopt(allMean{i},allCovar{i},[],r);
    j = (pconfigs(:,i) < 1e-10);
    pconfigs(j,i) = 0;
  catch exception
    warning(exception.identifier,exception.message)
    %Do nothing, unattainable return will be represented by NaN's
  end 

end


